package com.isunland.managesystem.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.widget.Toast;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import com.amap.api.location.AMapLocation;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isunland.managesystem.BuildConfig;
import com.isunland.managesystem.R;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.AppManager;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.Internal;
import com.isunland.managesystem.utils.LocationUtil;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.SharedPreferencesUtil;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import org.json.JSONException;

/**
 * 对象功能:
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: HuXiaoDan
 * 创建时间: 2017/3/14 10:03
 */
public class GuideMenuNewActivity extends SingleFragmentActivity {
  private static final int MSG_SET_ALIAS = 1001;
  private static final int MSG_SET_TAG = 1002;
  //    private BaseVolleyActivity mActivity;
  private final Handler mHandler = new MyHandler();
  private final TagAliasCallback mAliasCallback = new MyTagAliasCallback();
  //    private static HintNumber mHintNumber;
  private long mExitTime;

  /**
   * 跳转不刷新,唯一
   *
   * @param context 上下文对象
   */
  protected static Intent newIntent(Context context) {
    Intent intent = new Intent();
    intent.setClass(context, GuideMenuNewActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);//设置不要刷新将要跳到的界面
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);//它可以关掉所要到的界面中间的activity
    return intent;
  }

  @Override protected Fragment createFragment() {
    return new GuideMenuNewFragment();
  }

  @Override protected void onCreate(Bundle savedInstanceState) {
    volleyPostTimeInternal();// 时间间隔初始化.
    setAliasAndTag();//登陆成功后设置极光的标签和别名.
    mActivity = this;
    startLocation();
    super.onCreate(savedInstanceState);
  }

  /** 开始定位 */
  private void startLocation() {
    LocationUtil.newInstance(this)
        .setSimpleLocationListener(new LocationUtil.SimpleCustomLocationListener() {
          @Override public void onLocationValid(AMapLocation location) {
            LogUtil.i(
                "customLocation=" + location.getLatitude() + ",long=" + location.getLongitude());
            setAliasAndTag();
          }

          @Override public void onLocationError() {

          }
        })
        .startLocation();
  }

  // 这是来自 JPush Example 的设置别名的 Activity 里的代码。一般 App 的设置的调用入口，在任何方便的地方调用都可以。
  private void setAliasAndTag() {

    String alias = CurrentUser.newInstance(this).getJobNumber();
    if (!TextUtils.isEmpty(alias)) {
      // 调用 Handler 来异步设置别名
      mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, alias));
    } else {
      LogUtil.i("jobNO不能为空");
    }

    String memberCode = CurrentUser.newInstance(this).getMemberCode();
    if (!TextUtils.isEmpty(memberCode)) {
      // 调用 Handler 来异步设置别名
      mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_TAG, memberCode));
    } else {
      LogUtil.i("memberCode不能为空");
    }
  }

  @Override public boolean onKeyDown(int keyCode, KeyEvent event) {

    // Auto-generated method stub
    switch (keyCode) {
      case KeyEvent.KEYCODE_BACK:
        // 判断是不是超过2秒又点击返回键，超过就toast一遍，小于2秒就退出
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
          Toast.makeText(this, R.string.sure_to_exit, Toast.LENGTH_SHORT).show();

          mExitTime = System.currentTimeMillis();
        } else {
          AppManager.getAppManager().finishAllActivity();
        }
        return true;
      default:
        break;
    }

    return super.onKeyDown(keyCode, event);
  }

  //

  @Override protected void onStop() {
    //		UmengUpdateAgent.forceUpdate(this);
    super.onStop();
  }

  @Override protected void onStart() {
    super.onStart();
    //forceUpgrade();
  }

  //@Override protected void onDestroy() {
  //  LocationUtil.newInstance(this).destroy();
  //  super.onDestroy();
  //}

  /**
   * 初始化时获取外勤时间间隔.
   */
  private void volleyPostTimeInternal() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_TIME_INTERNAL);
    HashMap<String, String> params = new HashMap<>();

    this.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String response) throws JSONException {
        try {

          Internal internal = new Gson().fromJson(response, Internal.class);
          if (internal == null) {
            return;
          }
          int mInternalTime = internal.getInteval();
          //					LogUtil.i("internal="+mInternalTime);
          SharedPreferencesUtil.setInt(GuideMenuNewActivity.this,
              SharedPreferencesUtil.INTERNAL_TIME, mInternalTime);
        } catch (JsonSyntaxException e) {
          LogUtil.e(TAG, "TimeInternalJsonerror", e);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {

        LogUtil.e(TAG, "TimeInternalError", arg0);
      }
    });
  }

  private class MyHandler extends Handler {
    @SuppressWarnings("all") @Override public void handleMessage(android.os.Message msg) {
      super.handleMessage(msg);
      switch (msg.what) {
        case MSG_SET_ALIAS:
          LogUtil.d("在handler中设置别名");
          // 调用 JPush 接口来设置别名。
          String alias = MyUtils.isPush(mActivity) ? (String) msg.obj : "";
          JPushInterface.setAliasAndTags(getApplicationContext(), alias, null, mAliasCallback);
          break;

        case MSG_SET_TAG:
          LogUtil.d("在handler中设置标签");
          // 调用 JPush 接口来设置别名。
          HashSet<String> tags = new LinkedHashSet<>();
          tags.add((String) msg.obj);
          tags.add("android");
          tags.add(BuildConfig.FLAVOR);
          tags.add(BuildConfig.BUILD_TYPE);
          tags.add(MyStringUtil.valueOf(MyUtils.getVersionCode(mActivity)));
          tags.add(MyUtils.getVersionName(mActivity));
          tags.add(CurrentUser.newInstance(GuideMenuNewActivity.this).getProvince());
          //根据配置,将tag清空
          tags = MyUtils.isPush(mActivity) ? tags : new LinkedHashSet<String>();
          JPushInterface.setAliasAndTags(getApplicationContext(), null, tags, mAliasCallback);
          break;
        default:
          LogUtil.i("未处理的信息: " + msg.what);
      }
    }
  }

  /**
   * 设置标签和别名的回调对象
   */
  private class MyTagAliasCallback implements TagAliasCallback {
    @Override public void gotResult(int code, String alias, Set<String> tags) {
      String logs;
      switch (code) {
        case 0:
          logs = "设置标签和别名成功";
          LogUtil.i(MyStringUtil.connect(logs, MyStringUtil.COMMA, alias, MyStringUtil.COMMA,
              MyStringUtil.valueOf(tags)));
          // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
          break;
        case 6002:
          logs = "设置标签和别名失败,将在60秒后重试";
          LogUtil.i(logs);
          // 延迟 60 秒来调用 Handler 设置别名
          mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
          break;
        default:
          logs = "设置标签和别名失败,错误码为 = " + code;
          LogUtil.e(logs);
      }
    }
  }
}
